<?php

namespace app\common\controller;

use app\admin\model\general\HhyConfig;
use app\common\library\traits\Jump;
use app\common\traits\JumpReturn;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Lang;
use think\facade\Validate;
use think\facade\View;
use think\facade\Event;
use think\facade\Config;

/**
 * 前台控制器基类.
 */
class Frontend extends BaseController
{
    //自定义 数据返回
    use JumpReturn;
    //系统配置
    protected $sysConfig;
    //配置类型
    protected $config_type="all";

    protected $model=null;

    public function _initialize()
    {
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $modulename = app()->http->getName();
        $controller = preg_replace_callback('/\.[A-Z]/', function ($d) {
            return strtolower($d[0]);
        }, $this->request->controller(), 1);

        $controllername = parseName($controller);
        $actionname = strtolower($this->request->action());

        $this->sysConfig=HhyConfig::configList($this->config_type);

        //站点关闭
        if ($this->sysConfig['basic']['site_status']=='0'){
            $this->failed('站点维护中....');
        }

        // 语言检测
        $lang = strip_tags(Lang::getLangSet());

        // 配置信息
        $config = [
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'moduleurl'      => rtrim(url("/{$modulename}", [], false), '/'),
            'language'       => $lang,
            'site'    =>$this->sysConfig['basic']
        ];
        // 加载当前控制器语言包
        $this->loadlang($this->request->controller());

        $this->assign('config', $config);

        $background = Config::get('fastadmin.login_background');

        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl').$background;
        $this->assign('bannar_background', $background);

        //获取当前配置的网站地址
        $this->domain = $this->request->domain();
        $this->assign("domain", $this->domain);

        $this->assign("durl", request()->url(true));

        if (Cache::has("bannar_dujitangs")){
            $dujitang=Cache::get("bannar_dujitangs");

            if(empty($dujitang)){
                $dujitang=$this->get_data();
            }
        }else{
            $dujitang=$this->get_data();
        }

        $this->assign("dujitang",$dujitang);

    }


    /**
     * @param string $msg
     * @param int $url
     * @return \think\response\Json
     * @throws \Exception
     */
    protected function failed($msg = '哎呀…亲…您访问的页面出现错误', $url = 0)
    {
        if ($this->request->isAjax()) {
            return self::JsonReturn($msg,0,$url);
        } else {
            $this->assign(compact('msg', 'url'));
            exit($this->fetch('public/error'));
        }
    }


    /***
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_data(){
        $page=Cache::get('page_mingjuu',1);
        $dujitang=Db::name("mingju")->field("id,content")->limit(20)->page($page)->select();
        if(!empty($dujitang)){
            $ids=[];
            $du=[];
            foreach ($dujitang as $k=>$v){
                $du[]=$v['content'];
                $ids[]=$v['id'];
            }
            $dujitang=$du;
        }
        Cache::set('page_mingjuu',$page+1);
        Cache::set("bannar_dujitangs",$dujitang,3600*24*30);
        return $dujitang;
    }


    /**
     * 加载语言文件.
     *
     * @param string $name
     */
    protected function loadlang($name)
    {
        if (strpos($name, '.')) {
            $_arr = explode('.', $name);
            if (count($_arr) == 2) {
                $path = $_arr[0].'/'.parseName($_arr[1]);
            } else {
                $path = strtolower($name);
            }
        } else {
            $path = parseName($name);
        }
        Lang::load(app()->getAppPath().'/lang/'.Lang::getLangset().'/'.$path.'.php');
    }

    /**
     * 渲染配置信息.
     *
     * @param mixed $name  键名或数组
     * @param mixed $value 值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [],
            is_array($name) ? $name : [$name => $value]);
    }

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->post('__token__');

        //验证Token
        if (!Validate::is($token, "token", ['__token__' => $token])) {
            $this->error(__('Token verification error'), '', ['__token__' => $this->request->buildToken()]);
        }

        //刷新Token
        $this->request->buildToken();
    }


    /**
     * @throws \Exception
     */
    public function _empty()
    {
        exit($this->fetch('public/false'));
    }

}
